import atexit
import shelve
import time
from functools import wraps
from config.settings import CACHE_PATH
from . import singleton


@singleton
class LocalCache():
    def __init__(self, filename):
        db = shelve.open(str(filename))
        self.db = db

        @atexit.register
        def cleanup():
            self.db.close()

    @staticmethod
    def now_time():
        return int(time.time())

    def get(self, key):
        # TODO: implement expire time
        value = self.db.get(key, [])
        return value

    def set(self, key, value):
        cache = self.get(key)
        if cache:
            print(f'{key}已存在')
            return
        self.db.setdefault(key, value)

    def close(self):
        self.db.close()


def file_cache(cache_path=CACHE_PATH):
    caches = LocalCache(CACHE_PATH)

    def _wrapped(func):
        @wraps(func)
        def __wrapped(*args, **kwargs):
            # TODO: Use md5 algorithm
            key = str(func.__name__) + str(args) + str(kwargs)
            result = caches.get(key)
            if not result:
                result = func(*args, **kwargs)
                if result:
                    caches.set(key, result)
            return result

        return __wrapped

    return _wrapped
